#include<bits/stdc++.h>
using namespace std;


struct Book{
	string title;
	string author;
	int state; // 0 表示在列 1表示借出 2表示归还但未排序 
};

bool sortBook(Book& b1,Book& b2){
	if(b1.author == b2.author){
		return b1.title < b2.title;
	}
	return b1.author < b2.author;
}

Book GetBookInfo(string tmp){
	Book b;
	auto iter = tmp.find(" by ");
	b.title = tmp.substr(1,iter-2);
	b.author = tmp.substr(iter+4); 
	b.state = 0;
	return b; 
}

int FindBookByTitile(string btitle,vector<Book>& books){
	int ix = 0;
	while(ix<books.size() && books[ix].title!=btitle){
		ix++;
	}
    if(ix == books.size())
	    return -1;
    return ix;
} 


void Shelve(vector<Book>& books){
	string t1,t2="";
	int ix =0;
	while(ix<books.size()){
		if(books[ix].state==0){
			t2 = books[ix].title;
		} else if(books[ix].state==2){
			if(t2!=""){
				cout<<"Put \""<<books[ix].title
					<<"\" after \""<<t2<<"\"\n";
			} else {
				cout<<"Put \""<<books[ix].title
					<< "\" first\n";
			}
            books[ix].state = 0;
    		t2 = books[ix].title;
		}
		ix++;
	}
    cout<<"END"<<endl;	
}

int main(){
	string tmp;
    vector<Book> books;
	while(getline(cin,tmp) && tmp!="END"){		
		Book b = GetBookInfo(tmp);
		books.push_back(b);
	}
	sort(books.begin(),books.end(),sortBook);
	
	while(getline(cin,tmp) && tmp != "END"){
		char op = tmp[0];
		if(op!='S'){
			auto ti = tmp.find("\"");
			string btitle = tmp.substr(ti+1,tmp.size()-1-ti-1);
			int pos = FindBookByTitile(btitle,books);
			if(op == 'B'){
				// BORROW btitle
				if(pos>=0 && pos<books.size()){
					books[pos].state = 1;
				}
			} else if(op=='R'){
				// RETURN 
				if(pos>=0 && pos<books.size()){
					books[pos].state = 2;
				}
			}
		} else {
			// SHELVE 
			Shelve(books);
			
		}	
	}
	return 0;
}
